﻿using System;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using ElectronicWMSA.Comm.ClassFiles;
using ElectronicWMSA.Comm.Forms.Message;
using WMSABL.SY;
using WMSAML.SY;
/****************************************
** 作者: LH
** 时间: 2017-02-23
*****************************************/
namespace ElectronicWMSA
{
    public partial class Main : Form
    {
        #region
        protected override CreateParams CreateParams
        {
            get
            {
                const int WS_MINIMIZEBOX = 0x00020000;  // Winuser.h中定义
                CreateParams cp = base.CreateParams;
                cp.Style = cp.Style | WS_MINIMIZEBOX;   // 允许最小化操作
                return cp;
            }
        }

        public static Main _Main = null;
        public Main()
        {
            InitializeComponent();
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            _Main = this;
        }

        private void Main_Load(object sender, EventArgs e)
        {
            this.MaximumSize = new Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);
            this.WindowState = FormWindowState.Maximized;
            this.DBind();
            this.Text = EWMSAClass.SYSTEMNAME;
        }
        #endregion

        #region DBind
        TUsers_BLL bll_TUsers = new TUsers_BLL();
        TUsers_Entity entity_TUsers = new TUsers_Entity();
        public void DBind()
        {
            this.labelUser.Text = "【用户:" + SystemVariable.User_Name + "】";
            this.DBindSystem_meun();
            this.SetModel();
            this.labelNo.Text = "版本:" + EWMSAClass.VERSION;
        }
        private void labTitle_Click(object sender, EventArgs e)
        {
            this.tabChildrenfrm.SelectedIndex = 0;
        }
        #endregion

        #region 绑定TreeView功能列表
        private void labdown_Click(object sender, EventArgs e)
        {
            this.treeViewpicMenu.ExpandAll();
        }

        private void labUP_Click(object sender, EventArgs e)
        {
            this.treeViewpicMenu.CollapseAll();
        }
        TSystemRegistBLL bll_SystemRegist = new TSystemRegistBLL();
        public void DBindSystem_meun()
        {
            this.treeViewpicMenu.Nodes.Clear();
            DataSet ds = new DataSet();
            ds = bll_SystemRegist.GetList_SystemMeun();
            DataTable dt = new DataTable();
            dt = ds.Tables[0];
            DataView dv = new DataView(dt);
            dv.RowFilter = "headID=0";
            foreach (DataRowView drv in dv)
            {
                TreeNode node = new TreeNode();
                node.Text = drv["Menu_Name"].ToString();
                node.ToolTipText = drv["Menu_Name"].ToString();
                node.Name = drv["ID"].ToString();
                node.ImageIndex = 2;
                node.SelectedImageIndex = 0;
                this.treeViewpicMenu.Nodes.Add(node);
                this.AddNodes(dt, node);
            }
        }
        public void AddNodes(DataTable dt, TreeNode node)
        {
            DataView dv = new DataView(dt);
            dv.RowFilter = "headID='" + node.Name + "'";
            foreach (DataRowView row in dv)
            {
                TreeNode replyNode = new TreeNode();
                replyNode.Text = row["Menu_Name"].ToString();
                replyNode.ToolTipText = row["Menu_Name"].ToString();
                replyNode.Name = row["ID"].ToString();
                node.ImageIndex = 1;
                node.SelectedImageIndex = 1;
                node.Nodes.Add(replyNode);
                AddNodes(dt, replyNode);
            }
        }
        #endregion

        #region 菜单对应页面
        private int nodeName = 0;
        private TabPage tbPage = null;
        private TabPage tbPageUp = null;
        private void treeViewpicMenu_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.LastNode == null)
            {
                if (nodeName > 0)
                    GetPermissionOpenFrm(nodeName);
            }
            else
                e.Node.SelectedImageIndex = 2;
        }
        private void GetPermissionOpenFrm(int menuID)
        {
            TSystemMenuEntity entity = new TSystemMenuEntity();
            entity = bll_SystemRegist.GetEntity_SystemMenu(menuID);
            if (entity != null)
            {
                TPermissions_BLL bll_TPermissions = new TPermissions_BLL();
                TPermissions_Entity entity_TPermissions = new TPermissions_Entity();
                entity_TPermissions = bll_TPermissions.GetEntityByType(menuID, "浏览");
                if (SystemVariable.UserRights != null && entity_TPermissions != null)
                {
                    if (SystemVariable.UserRights.Contains(entity_TPermissions.ID.ToString()))
                    {
                        SystemVariable.Menu_ID = menuID;
                        this.AddTab(entity.Url1, entity.Menu_Name, GetForm(entity.Url1));
                    }
                    else
                        MessageClass.warning("无权限！");
                }
                else
                    MessageClass.warning("无权限！");
            }
        }

        /// <summary>
        /// 添加选项卡页面显示窗体信息
        /// </summary>
        /// <param name="id">选项卡id</param>
        /// <param name="name">选项卡名称</param>
        /// <param name="newForm">所要加载的窗体</param>
        public void AddTab(string id, string name, Form newForm)
        {
            if (newForm != null)
            {
                if (ErgodicModiForm(id, tabChildrenfrm))
                {
                    tbPage = new TabPage();
                    tbPage.Name = id;
                    tbPage.Text = name;
                    tabChildrenfrm.TabPages.Add(tbPage);
                    tbPageUp = tbPage;

                    newForm.Dock = DockStyle.Fill;
                    newForm.TopLevel = false;
                    newForm.Show();
                    tbPage.Controls.Add(newForm);
                }
                tabChildrenfrm.SelectedTab = tbPage;
            }
        }

        /// <summary>
        /// 添加窗体
        /// </summary>
        /// <param name="MainTabControlKey">选项卡的键值</param>
        /// <param name="objTabControl">要添加到的TabControl对象</param>
        /// <returns></returns>
        private Boolean ErgodicModiForm(string MainTabControlKey, TabControl objTabControl)
        {
            foreach (Control con in objTabControl.Controls)
            {
                tbPage = (TabPage)con;
                if (tbPage.Name == MainTabControlKey) return false;
            }
            return true;
        }

        private void tabChildrenfrm_SelectedIndexChanged(object sender, EventArgs e)
        {
            tbPage = tabChildrenfrm.SelectedTab;
        }

        public Form GetForm(string strFrom)
        {
            Form frm = null;
            try
            {
                if (strFrom == "")
                {
                    MessageClass.warning("此功能未开放！");
                }
                #region 占屏显示
                else if (strFrom == "ElectronicWMSA.Warehouse.WarehouseFrm")
                {
                    ElectronicWMSA.Warehouse.WarehouseFrm frm1 = new Warehouse.WarehouseFrm();
                    frm1.ShowDialog();
                }
                else if (strFrom == "ElectronicWMSA.Warehouse.Warehouse_PartsLocationFrm")
                {
                    ElectronicWMSA.Warehouse.Warehouse_PartsLocationFrm frm1 = new Warehouse.Warehouse_PartsLocationFrm();
                    frm1.ShowDialog();
                }
                else if (strFrom == "ElectronicWMSA.Warehouse.Warehouse_OrderPickingRouteFrm")
                {
                    ElectronicWMSA.Warehouse.Warehouse_OrderPickingRouteFrm frm1 = new Warehouse.Warehouse_OrderPickingRouteFrm();
                    frm1.ShowDialog();
                }
                else if (strFrom == "ElectronicWMSA.Warehouse.Warehouse_OptimizationFrm")
                {
                    ElectronicWMSA.Warehouse.Warehouse_OptimizationFrm frm1 = new Warehouse.Warehouse_OptimizationFrm();
                    frm1.ShowDialog();
                }
                else if (strFrom == "ElectronicWMSA.Warehouse.List_PickingFrm1")
                {
                    ElectronicWMSA.Warehouse.List_PickingFrm1 frm1 = new Warehouse.List_PickingFrm1();
                    frm1.ShowDialog();
                }
                #endregion
                else
                {
                    //类型被包含在namspace里面就必须要用包含namespace的完整路径来获取类型信息
                    Type type = Type.GetType(strFrom);
                    frm = (Form)Activator.CreateInstance(type);
                }
            }
            catch (Exception)
            {
                MessageClass.error("打开界面异常！");
            }
            return frm;
        }

        private void treeViewpicMenu_Leave(object sender, EventArgs e)
        {
            if (treeViewpicMenu.SelectedNode != null)
            {
                //让选中项背景色呈现红色
                treeViewpicMenu.SelectedNode.BackColor = Color.CornflowerBlue;
               
            }
        }

        private void treeViewpicMenu_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            if (treeViewpicMenu.SelectedNode != null)
            {
                treeViewpicMenu.SelectedNode.BackColor = Color.Empty;
                //treeViewpicMenu.SelectedNode.ForeColor = Color.DimGray;
            }
        }
        private void treeViewpicMenu_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            nodeName = 0;
            if (e.Node.LastNode == null)
            {
                nodeName = Convert.ToInt32(e.Node.Name);
            }
            //判断是否是右击
            if (e.Button == MouseButtons.Right)
            {
                //选中点击的节点
                treeViewpicMenu.SelectedNode = e.Node;
                if (nodeName > 0)
                {
                    //获取节点区域的右下角坐标值
                    Point pos = new Point(e.Node.Bounds.X + e.Node.Bounds.Width, e.Node.Bounds.Y + e.Node.Bounds.Height);
                    //在选中的节点的右下角，弹出右键菜单，并设定控制者为treeView
                    contextMenuStrip1.Show(treeViewpicMenu, pos);
                }
            }
        }

        private void tsMiOpenMeun_Click(object sender, EventArgs e)
        {
            if (nodeName > 0)
                GetPermissionOpenFrm(nodeName);
        }
        #endregion

        #region 网站
        private void labAddress_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process ie = new System.Diagnostics.Process();
            ie.StartInfo.FileName = "IEXPLORE.EXE";
            ie.StartInfo.Arguments = "http://www.innti.com";
            ie.Start();
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            this.labeltime.Text = "日期/时间: " + "【" + Convert.ToString(DateTime.Now.ToLocalTime()) + "】";
        }
        #endregion

        #region 注销
        public int FDIDFrmIsClose = 0;
        private void labelLogout_Click(object sender, EventArgs e)
        {
            if (MessageClass.enquire("注销系统！") == DialogResult.OK)
            {
                this.Hide();
                entity_TUsers = bll_TUsers.GetEntityByID(SystemVariable.User_ID);
                entity_TUsers.LoginStatus = 0;
                bll_TUsers.Update(entity_TUsers);
                Login frm = new Login();
                frm.ShowDialog();
                System.Environment.Exit(0);
            }
        }

        private void btnMini_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageClass.enquire("退出系统！") == DialogResult.OK)
            {
                entity_TUsers = bll_TUsers.GetEntityByID(SystemVariable.User_ID);
                entity_TUsers.LoginStatus = 0;
                bll_TUsers.Update(entity_TUsers);
                System.Environment.Exit(0);
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void btnCloseFrom_Click(object sender, EventArgs e)
        {
            if (MessageClass.enquire("退出系统！") == DialogResult.OK)
            {
                entity_TUsers = bll_TUsers.GetEntityByID(SystemVariable.User_ID);
                entity_TUsers.LoginStatus = 0;
                bll_TUsers.Update(entity_TUsers);
                System.Environment.Exit(0);
              //  Process.GetCurrentProcess().Kill();
                KillAppProcess(System.Diagnostics.Process.GetCurrentProcess().ProcessName);
                Application.Exit();
            }
        }
        #region 结束进程
        /// <summary>
        /// 结束进程
        /// </summary>
        /// <param name="appName"></param>
        public void KillAppProcess(string appName)
        {
            Process[] allProcess = Process.GetProcesses();
            foreach (Process p in allProcess)
            {
                //MessageBox.Show(p.ProcessName);//进?程¨¬名?称?没?有®D".exe"
                if (p.ProcessName.ToLower() + ".exe" == appName.ToLower())
                {
                    for (int i = 0; i < p.Threads.Count; i++)
                    {
                        p.Threads[i].Dispose();
                    }
                    p.Kill();
                }
            }
        }

        #endregion
        #endregion

        #region 密码修改
        private void labelUpdatePWD_Click(object sender, EventArgs e)
        {
            TSystemMenuEntity entity = new TSystemMenuEntity();
            entity = bll_SystemRegist.GetEntity_SystemMenu(13);
            if (entity != null)
                this.AddTab(entity.Url1, entity.Menu_Name, GetForm(entity.Url1));
        }
        #endregion

        #region  菜单焦点
       

        #region 失去焦点停止闪烁并选中
        private TreeView treeView;
        private System.Threading.Thread th;
        private int blinkRate;
        private bool isBlink = false;
        public void BlinkTreeNodeRenderer(TreeView treeView)
        {
            Initialize(treeView, 1);
        }

        public void BlinkTreeNodeRenderer(TreeView treeView, int blinkRate)
        {
            Initialize(treeView, blinkRate);
        }

        private void Initialize(TreeView treeView, int blinkRate)
        {
            if (blinkRate < 0 || blinkRate > 1000)
            {
                throw new ArgumentOutOfRangeException("blinkRate", "blinkRate应大于0且小于1000");
            }
            this.treeView = treeView;
            this.blinkRate = blinkRate;
            this.treeView.HideSelection = false;
            this.treeView.DrawMode = TreeViewDrawMode.OwnerDrawText;
            this.treeView.DrawNode += new DrawTreeNodeEventHandler(treeView_DrawNode);
            this.treeView.Disposed += new EventHandler(treeView_Disposed);

            this.th = new System.Threading.Thread(new System.Threading.ThreadStart(Blink));
            this.th.IsBackground = true;
            this.th.Start();
        }

        //一定的时间间隔更改isBlink的值，并使当前选择节点区域无效（不用对整个控件无效），发送绘制消息
        private void Blink()
        {
            int sleepTime = 1000 / blinkRate;
            while (true)
            {
                System.Threading.Thread.Sleep(sleepTime);
                isBlink = !isBlink;
                treeView.BeginInvoke(new MethodInvoker(delegate()
                {
                    if (treeView.SelectedNode != null && treeView.Focused)
                    {
                        treeView.Invalidate(treeView.SelectedNode.Bounds);
                    }
                }));
            }
        }

        private void treeView_DrawNode(object sender, DrawTreeNodeEventArgs e)
        {
            //设置为false由用户绘制而非操作系统绘制
            e.DrawDefault = false;
            if ((e.State & TreeNodeStates.Selected) != 0 || (e.State & TreeNodeStates.Focused) != 0)
            {
                //判断节点是否已选择或者已获得焦点，如果是true则绘制高亮显示、焦点框
                e.Graphics.FillRectangle(new SolidBrush(SystemColors.Highlight), e.Bounds);
                using (Pen focusedPen = new Pen(Color.Black))
                {
                    focusedPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
                    Rectangle focusedBounds = e.Bounds;
                    focusedBounds.Size = new Size(e.Bounds.Width - 1, e.Bounds.Height - 1);
                    e.Graphics.DrawRectangle(focusedPen, focusedBounds);
                }
                //节点根据isBlink状态绘制显示文本
                if (isBlink || !treeView.Focused)
                {
                    TextRenderer.DrawText(e.Graphics, e.Node.Text, e.Node.NodeFont, e.Bounds, Color.White);
                }
            }
            else
            {
                //绘制未被选择的其余节点
                TextRenderer.DrawText(e.Graphics, e.Node.Text, e.Node.NodeFont, e.Bounds, e.Node.ForeColor);
            }
        }

        private void treeView_Disposed(object sender, EventArgs e)
        {
            th.Abort();
            th = null;
        }
        #endregion
        #endregion

        #region 移动
        Point downPoint;
        private void panelTop_MouseDown(object sender, MouseEventArgs e)
        {
            downPoint = new Point(e.X, e.Y);
        }

        private void panelTop_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Location = new Point(this.Location.X + e.X - downPoint.X,
                    this.Location.Y + e.Y - downPoint.Y);
            }
        }
        #endregion

        #region 右键选中
        private void tabChildrenfrm_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                for (int i = 0; i < tabChildrenfrm.TabPages.Count; i++)
                {
                    TabPage tp = tabChildrenfrm.TabPages[i];
                    if (tabChildrenfrm.GetTabRect(i).Contains(new Point(e.X, e.Y)))
                    {
                        tabChildrenfrm.SelectedTab = tp;
                        break;
                    }
                }
            }
        }
        #endregion

        #region 移除标签
        public void CloseTabPages()
        {
            if (tbPage.Text != "首页")
            {
                GetForm(tbPage.Name).Close();
                tbPage.Dispose();
                tabChildrenfrm.SelectedIndex = tabChildrenfrm.TabCount - 1;
            }
        }
        public void CloseTabPageElse()
        {
            for (int i = 0; i < tabChildrenfrm.TabPages.Count; i++)
            {
                TabPage tp = tabChildrenfrm.TabPages[i];
                if (tp.Text != "首页" && tp.Text != tbPage.Text)
                {
                    tp.Dispose();
                    GetForm(tp.Name).Close();
                    i -= 1;
                }
            }
            //采用无刷新控件时
            //tabChildrenfrm.Refresh();
            tabChildrenfrm.SelectedIndex = 1;
        }
        public void CloseAllTabPages()
        {
            for (int i = 0; i < tabChildrenfrm.TabPages.Count; i++)
            {
                TabPage tp = tabChildrenfrm.TabPages[i];
                if (tp.Text != "首页")
                {
                    tp.Dispose();
                    GetForm(tp.Name).Close();
                    i -= 1;
                }
            }
        }
        #endregion

        #region   菜单隐藏
        private void labHidd_Click(object sender, EventArgs e)
        {
            sp.Panel1Collapsed = true;
        }
        private void labShow_Click(object sender, EventArgs e)
        {
            sp.Panel1Collapsed = false;
        }
        #endregion

        #region 设置首页显示模块
        private void SetModel()
        {
            TSystemMenuEntity entity = new TSystemMenuEntity();
            TPermissions_BLL bll_TPermissions = new TPermissions_BLL();
            TPermissions_Entity entity_TPermissions = new TPermissions_Entity();
            if (1 > 2)
            {
                entity = new TSystemMenuEntity();
                entity_TPermissions = new TPermissions_Entity();

                entity = bll_SystemRegist.GetEntity_SystemMenu(321);
                if (entity == null) return;
                entity_TPermissions = bll_TPermissions.GetEntityByType(321, "浏览");
                if (SystemVariable.UserRights != null && entity_TPermissions != null)
                {
                    if (SystemVariable.UserRights.Contains(entity_TPermissions.ID.ToString()))
                        this.btn12.Enabled = true;
                    else
                        this.btn12.Enabled = false;
                }
            }
        }
        #region 1

         //拣货路线
        private void btn12_Click(object sender, EventArgs e)
        {
            GetPermissionOpenFrm(39);
        }

        //拣货查询
        private void btn13_Click(object sender, EventArgs e)
        {
        GetPermissionOpenFrm(58);
        }

        //进度展示
        private void btn14_Click(object sender, EventArgs e)
        {
            GetPermissionOpenFrm(43);
        }

        //部品定位
        private void btn15_Click(object sender, EventArgs e)
        {
            GetPermissionOpenFrm(38);
        }
        #endregion

        #region 2
        //仓库信息
        private void btn21_Click(object sender, EventArgs e)
        {
              GetPermissionOpenFrm(30);
        }

        //区域信息
        private void btn22_Click(object sender, EventArgs e)
        {
            GetPermissionOpenFrm(31);
        }

        //仓位信息
        private void btn23_Click(object sender, EventArgs e)
        {
            GetPermissionOpenFrm(32);
        }

        //库存管理
        private void btn24_Click(object sender, EventArgs e)
        {
            GetPermissionOpenFrm(33);
        }

        //部品出库
        private void btn25_Click(object sender, EventArgs e)
        {
           GetPermissionOpenFrm(35);
        }
        #endregion

       #region  3
        
        private void button31_Click(object sender, EventArgs e)
        {
            GetPermissionOpenFrm(47);
        }

        private void button32_Click(object sender, EventArgs e)
        {
           GetPermissionOpenFrm(48);
        }

        private void button33_Click(object sender, EventArgs e)
        {
            GetPermissionOpenFrm(51);
        }

        private void button34_Click(object sender, EventArgs e)
        {
            GetPermissionOpenFrm(50);
        }

        private void button35_Click(object sender, EventArgs e)
        {
            GetPermissionOpenFrm(37);
        }
        #endregion

        private void btnPickingNO_Click(object sender, EventArgs e)
        {
            GetPermissionOpenFrm(46);
        }

        #endregion

        private void treeViewpicMenu_AfterSelect(object sender, TreeViewEventArgs e)
        {

        }
    }
}
